const {ACTION_CODE, SCORE_POINT} = require('./mahjongConstants.js');

// 简单算分
function getScoreInfo(winnerPlayerIds, mahjongGame) {
  const result = {}
  mahjongGame.playerSequence.forEach(playerId => {
    result[playerId] = {
      score: 0,
      scorePoints: []
    }
  })
  winnerPlayerIds = [].concat(winnerPlayerIds)
  // TODO: 流局
  const isLiuJu = winnerPlayerIds.length === 0
  // 点炮
  const isDianPao = winnerPlayerIds.length > 1 || winnerPlayerIds[0] !== mahjongGame.currentPlayerId
  mahjongGame.playerSequence.forEach(playerId => {
    const player = mahjongGame.players[playerId]
    // 杠
    const gangGroups = player.groupCards.filter(groupCard => groupCard.actionCode & ACTION_CODE.Gang)
    gangGroups.forEach(gangGroup => {
      _addScorePoint(result[playerId].scorePoints, gangGroup.actionCode)
      // 明杠，从被杠的玩家扣分
      if (gangGroup.actionCode === ACTION_CODE.MingGang) {
        result[playerId].score += SCORE_POINT.Gang
        result[gangGroup.from].score -= SCORE_POINT.Gang
      } else { // 暗杠或碰后杠从其他玩家扣分
        mahjongGame.playerSequence.forEach(otherPlayerId => {
          if (otherPlayerId !== playerId) {
            result[otherPlayerId].score -= SCORE_POINT.Gang
            result[playerId].score += SCORE_POINT.Gang
          }
        })
      }
    })
  })
  // 胡
  if (isLiuJu) {
    // 不用处理
  } else if (isDianPao) {
    result[mahjongGame.currentPlayerId].scorePoints.push({ACTION_CODE: ACTION_CODE.DianPao, count: winnerPlayerIds.length})
    winnerPlayerIds.forEach(playerId => {
      result[playerId].score += SCORE_POINT.DianPao
      result[playerId].scorePoints.push({ACTION_CODE: ACTION_CODE.Hu, count: 1})
      result[mahjongGame.currentPlayerId].score -= SCORE_POINT.DianPao
    })
  } else { // 自摸
    mahjongGame.playerSequence.forEach(playerId => {
      if (playerId !== mahjongGame.currentPlayerId) {
        result[playerId].score -= SCORE_POINT.ZiMo
        result[mahjongGame.currentPlayerId].score += SCORE_POINT.ZiMo
      }
    })
    result[mahjongGame.currentPlayerId].scorePoints.push({ACTION_CODE: ACTION_CODE.ZiMo, count: 1})
  }
  return result
}

function _addScorePoint(scorePoints, actionCode) {
  const scorePoint = scorePoints.find(item => item.ACTION_CODE === actionCode)
  if (scorePoint) {
    scorePoint.count += 1
  } else {
    scorePoints.push({ACTION_CODE: actionCode, count: 1})
  }
}

module.exports = getScoreInfo;